import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Button, Icon } from 'antd';
import List from './List';
import Dialog from './Dialog';
import constructMenu from './../../utils/constructMenu';

const Menu = ({ dispatch, menu, loading }) => {
    const { list, pagination, currentItem, modalVisible, modalType } = menu;
    let tempData = constructMenu(list);

    const dialogProps = {
        item: modalType === 'Create' ? {} : currentItem,
        visible: modalVisible,
        maskClosable: false,
        confirmLoading: loading.effects['menu/update'],
        title: `${modalType === 'Create' ? modalType+' Menu' : modalType+' Menu'}`,
        onCreate (values) {
            if(modalType === 'Update'){
                dispatch({
                    type: 'menu/update',
                    payload: { values },
                });
            } else {
                dispatch({
                    type: 'menu/create',
                    payload: { values },
                })
            }
        },
        onCancel () {
            dispatch({
                type: 'menu/hideModal',
                payload: {
                    modalType: 'Create',
                    currentItem: {}
                },
            })
        },
    };

    const onCreate = () => {
        dispatch({
            type: 'menu/showModal',
            payload: {
                modalType: 'Create',
            },
        })
    };
    const listProps = {
        dataSource: tempData,
        loading: loading.effects['menu/query'],
        pagination,
        onChange (page) {
            console.log(page);
        },
        onDeleteItem (id) {
            dispatch({
                type: 'menu/delete',
                payload: id,
            })
        },
        onEditItem (item) {
            dispatch({
                type: 'menu/showModal',
                payload: {
                    modalType: 'Update',
                    currentItem: item,
                },
            })
        },
        onCreate(parentID) {
            let temp = {};
            temp.pid = parentID;
            dispatch({
                type: 'menu/showModal',
                payload: {
                    modalType: 'Create Children',
                    currentItem: temp
                },
            })
        }
    };

    return (
        <div style={{padding: 20,margin: 0}}>
            <Button type="primary" onClick={ onCreate }><Icon type="plus"/>新增一级菜单</Button>
            <List {...listProps} />
            { modalVisible && <Dialog {...dialogProps} /> }
        </div>
    )
};

Menu.propTypes = {
    menu: PropTypes.object,
    location: PropTypes.object,
    dispatch: PropTypes.func,
    loading: PropTypes.object,
};

export default connect(({ menu, loading }) => ({ menu, loading }))(Menu)
